package com.nutstudy.springcloud.lb.impl;

import com.nutstudy.springcloud.lb.LoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author: HyoJoo-W
 * @date: 2021-07-31 13:33
 * @description:
 */

@Slf4j
@Component
public class NutLB implements LoadBalancer
{
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances)
    {
        //要访问的服务实例索引index = 第几次访问 % 服务实例的数量
        int index = getAndIncrement() % serviceInstances.size();


        return serviceInstances.get(index);
    }

    public final int getAndIncrement()
    {
        int current;
        int next;
        do
        {
            current = this.atomicInteger.get();
            next = current >= Integer.MAX_VALUE ? 0 : current + 1;
        } while (!this.atomicInteger.compareAndSet(current, next));

        log.info("next(第几次访问次数): " + next);

        return next;
    }
}
